<template>
  <div>
    <svg-icon :icon-class="isFullscreen?'exit-fullscreen':'fullscreen'" @click="click"/>
  </div>
</template>

<script>
import screenfull from 'screenfull'

export default {
  name: 'Screenfull',
  data() {
    return {
      isFullscreen: false,
    }
  },
  mounted() {
    this.init()
    // 监听路由变化，以便在全屏状态下切换标签页时也能更新样式
    this.$router.afterEach(this.handleRouteChange)
  },
  beforeDestroy() {
    this.destroy()
    // 移除路由监听
    this.$router.afterEach(null)
  },
  methods: {
    click() {
      if (!screenfull.isEnabled) {
        this.$message({message: '你的浏览器不支持全屏', type: 'warning'})
        return false
      }

      // 获取当前激活的标签页内容区域
      const appMainElement = document.querySelector('.app-main');

      if (appMainElement) {
        screenfull.toggle(appMainElement)
      } else {
        // 如果找不到特定元素，则全屏整个页面
        screenfull.toggle()
      }
    },
    change() {
      this.isFullscreen = screenfull.isFullscreen
      // 在全屏状态改变时立即更新高度
      this.$nextTick(() => {
        this.updateAppMainHeight()
      })
    },
    // 更新app-main元素高度的方法
    updateAppMainHeight() {
      // 获取app-main元素
      const appMainElement = document.querySelector('.app-container');
      const appMainElement2 = document.querySelector('.health-report-container');

      if (appMainElement2) {
        if (this.isFullscreen) {
          // 全屏时设置高度为100%
          appMainElement2.style.minHeight = '100vh';
        } else {
          appMainElement2.style.minHeight = 'calc(100vh - 84px)';
        }
      } else if (appMainElement) {
        if (this.isFullscreen) {
          // 全屏时设置高度为100%
          appMainElement.style.minHeight = '100vh';
        } else {
          appMainElement.style.minHeight = 'calc(100vh - 84px)';
        }
      }
    },
    // 处理路由变化的方法
    handleRouteChange() {
      // 如果当前处于全屏状态，路由变化时更新app-main高度
      setTimeout(()=>{this.updateAppMainHeight()},1000)
      // this.$nextTick(() => {
      //   this.updateAppMainHeight()
      // })
    },
    init() {
      if (screenfull.isEnabled) {
        screenfull.on('change', this.change)
      }
    },
    destroy() {
      if (screenfull.isEnabled) {
        screenfull.off('change', this.change)
      }
    }
  }
}
</script>

<style scoped>
.screenfull-svg {
  display: inline-block;
  cursor: pointer;
  fill: #5a5e66;;
  width: 20px;
  height: 20px;
  vertical-align: 10px;
}
</style>
